using System;
using System.Collections.Generic;
using System.Text;
using org.apache.mina.common;

namespace PDSClient.Utils.IO.Impl
{
    public class SocketConnectionListener : IoHandlerAdapter 
    {
        public override void  sessionOpened(IoSession session)
        {
            SocketConnection conn = (SocketConnection)session.getAttachment();
            //logging logger.log(Level.FINE, "opened session {0}", session);
            IConnectionListener listener = conn.ConnectionListener;
            listener.Connected(conn);
        }

        public override void sessionClosed(IoSession session)
        {
            SocketConnection conn = (SocketConnection)session.getAttachment();
            //logging logger.log(Level.FINE, "disconnect on {0}", conn);
            IConnectionListener listener = conn.ConnectionListener;
            listener.Disconnected(conn);
        }

        public override void exceptionCaught(IoSession session, Exception cause)
        {
            SocketConnection conn = (SocketConnection)session.getAttachment();
            //logging logger.logThrow(Level.FINER, exception, "exception on {0}", conn);
            if (conn == null)
                return;

            IConnectionListener listener = conn.ConnectionListener;
            listener.ExceptionThrown(conn, cause);
        }

        public override void messageReceived(IoSession session, object message)
        {
            SocketConnection conn = (SocketConnection)session.getAttachment();
            
            /*
            if (logger.isLoggable(Level.FINEST))
            {
                logger.log(Level.FINEST, "recv on {0}: {1}", conn, message);
            }
            */

            ByteBuffer buf = (ByteBuffer)message;
            try
            {
                conn.Filter.FilterReceive(conn, buf);
            }
            catch (Exception e)
            {
                //logging logger.logThrow(Level.FINER, e, "exception in recv of {0}:", buf);
                throw e;
            }
        }
    }
}
